--[[
Adds MainAssist and MainTank icons to unit frames

    Elements handled: .MainAssist, .MainTank

--]]

local parent = debugstack():match[[\AddOns\(.-)\]]
local global = GetAddOnMetadata(parent, 'X-oUF')
assert(global, 'X-oUF needs to be defined in the parent add-on.')
local oUF = _G[global]

local function Update(self, event)
    if GetNumRaidMembers()>0 then
        for raidIndex = 1, MAX_RAID_MEMBERS do
            
            --So ugly.
            local name, _, _, _, _, _, _, _, _, role = GetRaidRosterInfo(raidIndex)
        
            if name and UnitIsUnit(name, self.unit) then
                if role == 'MAINTANK' and self.MainTank then
                    self.MainTank:Show()
                    if self.MainAssist then self.MainAssist:Hide() end
                elseif role == 'MAINASSIST' and self.MainAssist then
                    self.MainAssist:Show()
                    if self.MainTank then self.MainTank:Hide() end
                else
                    if self.MainAssist then self.MainAssist:Hide() end
                    if self.MainTank then self.MainTank:Hide() end
                end
            end
            
        end
    else
        if self.MainAssist then self.MainAssist:Hide() end
        if self.MainTank then self.MainTank:Hide() end
    end
    
end

local function Enable(self, unit)
    if(self.MainAssist or self.MainTank) then
        self:RegisterEvent('RAID_ROSTER_UPDATE', Update)

        if(self.MainAssist:IsObjectType('Texture') and not self.MainAssist:GetTexture()) then
            self.MainAssist:SetTexture([[Interface\GroupFrame\UI-GROUP-MAINASSISTICON]])
        end
    
        if(self.MainTank:IsObjectType('Texture') and not self.MainTank:GetTexture()) then
            self.MainTank:SetTexture([[Interface\GroupFrame\UI-GROUP-MAINTANKICON]])
        end
    
        return true
    end
end

local function Disable(self)
    if(self.MainAssist or self.MainTank) then
        self:UnregisterEvent('RAID_ROSTER_UPDATE', Update)
    end
end

oUF:AddElement('MainAssist', Update, Enable, Disable)